package com.liannong.controller;

import com.liannong.common.Result;
import com.liannong.service.TraceCodeService;
import com.liannong.vo.ProductVO;
import com.liannong.vo.TraceCodeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/trace-code")
@Api(tags = "溯源码管理")
public class TraceCodeController {

    private static final Logger logger = LoggerFactory.getLogger(TraceCodeController.class);

    @Autowired
    private TraceCodeService traceCodeService;

    /**
     * 生成溯源码
     * @param origin 产地
     * @return 溯源码信息
     */
    @PostMapping("/save")
    @ApiOperation("生成溯源码")
    public Result save(
            @ApiParam(value = "产地", required = true) @RequestParam String origin) {
        try {
            TraceCodeVO traceCodeVO = traceCodeService.generateTraceCode(origin);
            return Result.success(traceCodeVO);
        } catch (Exception e) {
            logger.error("生成溯源码失败", e);
            return Result.error("500", e.getMessage());
        }
    }

    /**
     * 根据溯源码获取信息
     * @param traceCode 溯源码
     * @return 溯源码信息
     */
    @GetMapping("/findByCode/{traceCode}")
    @ApiOperation("根据溯源码查询基本信息")
    public Result findByCode(
            @ApiParam(value = "溯源码", required = true) @PathVariable String traceCode) {
        try {
            TraceCodeVO traceCodeVO = traceCodeService.getByTraceCode(traceCode);
            return Result.success(traceCodeVO);
        } catch (Exception e) {
            logger.error("查询溯源码信息失败", e);
            return Result.error("500", e.getMessage());
        }
    }

    /**
     * 根据溯源码获取完整产品信息
     * @param traceCode 溯源码
     * @return 产品详细信息
     */
    @GetMapping("/product/{traceCode}")
    @ApiOperation("根据溯源码查询产品完整信息")
    public Result getProductByTraceCode(
            @ApiParam(value = "溯源码", required = true) @PathVariable String traceCode) {
        try {
            ProductVO productVO = traceCodeService.getProductByTraceCode(traceCode);
            return Result.success(productVO);
        } catch (Exception e) {
            logger.error("根据溯源码查询产品信息失败", e);
            return Result.error("500", e.getMessage());
        }
    }
} 